package net.moonj.UDPUI.udp;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.nio.charset.Charset;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioDatagramChannel;
import net.moonj.UDPUI.App;

public class UDPServer {
	
	public UDPServer(){
		init();
	}
	/**
	 * 
	 * @param text
	 * @param host
	 * @param port
	 * @throws IOException
	 *             UnknownHostException
	 */
	public void sendAssignmentByOS(String text, String host, int port) throws IOException {
		
		/*
		 * 如果处于监听模式，则采用localport，否则让操作系统自己分配
		 * */
		
		/** 1、建立udp socket端点 */
		DatagramSocket s = null ;

		if(App.instance().listen.isSelected()){
			sendViaChannel(text, host, port);
			return ;
		}else{
			s = new DatagramSocket();
		}
		
		/**
		 * 2、提供数据，封装打包 ---DatagramPacket(byte[] buf, int length, InetAddress
		 * address, int port)
		 */

		byte[] bs = text.getBytes();
		DatagramPacket dp = new DatagramPacket(bs, bs.length, InetAddress.getByName(host), port);

		/** 3、使用send发送 */
		s.send(dp);

		/** 4、关闭资源 */
		s.close();
		

	}

	private Bootstrap bootstrap;
	private NioEventLoopGroup workGroup;
	private Channel channel;

	public void listenSync(int listenPort) {
        try {
        	channel = bootstrap.bind(listenPort).sync().channel();
        } catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
	public void closeListenSync(){
		try {
			channel.close().sync();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
	public void init(){
		bootstrap = new Bootstrap();
		workGroup = new NioEventLoopGroup();
		bootstrap.group(workGroup).channel(NioDatagramChannel.class).option(ChannelOption.SO_BROADCAST, true)
				.handler(new ChannelInitializer<NioDatagramChannel>() {
					@Override
					protected void initChannel(NioDatagramChannel ch) throws Exception {
						ChannelPipeline pipeline = ch.pipeline();
						pipeline.addLast(new UdpEchoHandler());
					}
				});
	}
	public void sendViaChannel(String text, String host, int port){
		try {
			channel.writeAndFlush(new io.netty.channel.socket.DatagramPacket(Unpooled.copiedBuffer(text, Charset.forName("utf8")),new InetSocketAddress(host,port))).sync();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		
	}
	public void close(){
		channel.close();
		workGroup.shutdownGracefully();
	}
	
}
